package wangjg.xuexiban.util.json;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;

/**
 * @author wangjg
 *
 */
public class GsonUtil {
	
	public static String bean2json(Object bean,Type type){
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()).setDateFormat(java.text.DateFormat.LONG).create();
		return gson.toJson(bean);
	}
	
	public static <T> T json2bean(String json, Type type){
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).setDateFormat(java.text.DateFormat.LONG).create();
		return gson.fromJson(json, type);
	}
	
	public static <T> T json2bean(String json, Class<T> clazz){
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).setDateFormat(java.text.DateFormat.LONG).create();
		return gson.fromJson(json, clazz);
	}
	
	public static <T> List<T> json2List(String json){
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).setDateFormat(java.text.DateFormat.LONG).create();
		Type type = new TypeToken<List<T>>(){}.getType();
		return gson.fromJson(json, type);
	}
	
	public static void main(String args[]){
		System.out.println();
	}
}

class DateDeserializer implements JsonDeserializer<Date>{
	public Date deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
		return new Date(arg0.getAsJsonPrimitive().getAsLong());
	}
}

class DateSerializer implements JsonSerializer<Date>{
	@Override
	public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
		return new JsonPrimitive(arg0.getTime());
	}
}
